package com.weishi.project.speedometer.domain;

import java.util.ArrayList;
import java.util.List;

/**
 * 指数滤波(EMA)
 * 参考：https://blog.csdn.net/qq_36490364/article/details/104522980
 */
public class EmaFilter {

    /**
     * 固定解算参数
     */
    private static final double p1 = 0.4;
    private static final double p2 = 0.002;

    /**
     * @param alist    List<Double> medians
     * @param constant 常量
     * @return
     */
    public static List<Double> ema(List<Double> alist, List<Double> medians, double constant) {
        List<Double> aa = new ArrayList<>();
        double x0 = alist.get(0);
        double a0 = x0;
        double b0 = x0;

        for (Double x : alist) {
            double at = (1 - p1) * a0 + p1 * x;
            double bt = (1 - p2) * b0 + p2 * x;
            aa.add(at - constant);
            medians.add(bt - constant);
            a0 = at;
            b0 = bt;
        }

        return aa;
    }

    public static List<Double> ema(List<Double> alist, double constant) {
        List<Double> aa = new ArrayList<>();
        double x0 = alist.get(0);
        double a0 = x0;
        double b0 = x0;

        for (Double x : alist) {
            double at = (1 - p1) * a0 + p1 * x;
            double bt = (1 - p2) * b0 + p2 * x;
            aa.add(at - constant);
            a0 = at;
            b0 = bt;
        }

        return aa;
    }
}
